#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@file_name: creating_non_blocking_socket.py
@date: 2025-07-29 13:51
@author: Falling Snow
@desc: 创建非阻塞IO
"""
import socket
import time
from typing import Any

if __name__ == '__main__':
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    server_address = ("127.0.0.1", 8000)
    server_socket.bind(server_address)
    server_socket.listen()
    # 设置非阻塞IO
    server_socket.setblocking(False)

    connections: list[tuple[socket.socket, Any]] = []

    try:
        while True:
            try:
                conn, addr = server_socket.accept()
                conn.setblocking(False)
                print(f"来自客户端{addr}的连接")
                connections.append((conn, addr))
            except OSError:
                pass
            for connect, client_address in connections:
                try:
                    buffer = b""
                    while buffer[-2:] != b"\r\n":
                        data = connect.recv(2)
                        if not data:
                            break
                        else:
                            buffer += data

                    print(f"当前客户端{client_address}发送的所有数据为: {buffer[:-2].decode()}")
                    connect.sendall(buffer)
                except OSError:
                    pass
            time.sleep(0.5)
    finally:
        server_socket.close()
